package com.xd.xinan.mh_ftp.service;

import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MhFtpService {

    FTPClient ftpClient;

    @Value("${ftp.ip}")
    private String ip;

    @Value("${ftp.port}")
    private int port;

    @Value("${ftp.userName}")
    private String userName;

    @Value("${ftp.userPassword}")
    private String userPassword;

    @Value("${ftp.timeout}")
    private int timeout;

    /**
     * 连接到服务器
     * @return
     */
    public boolean connectFtpServer() {
        if (ftpClient != null && ftpClient.isConnected()) {
            return true;
        }
        /**
         * 连接 FTP 服务器
         * 如果连接失败，则此时抛出异常，如ftp服务器服务关闭时，抛出异常：
         * java.net.ConnectException: Connection refused: connect
         */
        try {
            ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(timeout*1000); //单位：s，如果超过就判定超时
            ftpClient.connect(ip, port);
            /**
             * 登录 FTP 服务器
             * 1）如果传入的账号为空，则使用匿名登录，此时账号使用 "Anonymous"，密码为空即可
             */
            if (StringUtils.isBlank(userName)) {
                ftpClient.login("Anonymous", "");
            } else {
                ftpClient.login(userName, userPassword);
            }
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftpClient.disconnect();
                return false;
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP服务器连接登录失败，请检查连接参数是否正确，或者网络是否通畅。");
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("FTP服务器连接登录失败，请检查连接参数是否正确，或者网络是否通畅。");
            return false;
        }
        return true;
    }

    /**
     * 使用完毕，应该及时关闭连接
     * 终止 ftp 传输
     * 断开 ftp 连接
     */
    public void closeFTPConnect()
    {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.abort();
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定路径下的文件列表
     */
    public Map<String, Object>  getFileNames(String filePath, String selName) throws Exception {

        Map<String, Object> fileNameDetails = new HashMap<String, Object>();
        List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
        fileNameDetails.put("ip", ip);
        fileNameDetails.put("code", 200);
        fileNameDetails.put("msg", "成功");

        if (connectFtpServer()) {
            try{
                String[] path = filePath.split(",");
                for (int j = 0; j < path.length; j++) {
                     /*更改ftp工作路径*/
                    if (ftpClient.changeWorkingDirectory(path[j])) {
                        /*设置被动模式*/
                        ftpClient.enterLocalPassiveMode();
                        /*获得文件名称*/
                        String[] files = ftpClient.listNames();
                        if (files == null || files.length == 0) {
                            continue;
                        }
                        for (int i = 0; i < files.length; i++) {
                            /*文件格式名称转换,解决中文乱码*/
                            String name = new String(files[i].getBytes("ISO-8859-1"), "utf-8");
                            if (name.equals(selName)) {
                                continue;
                            }
                            int finalJ = j;
                            Map<String, String> item = new HashMap<String, String>(){{
                                put("path", path[finalJ]);
                                put("filename", name);
                            }};
                            fileList.add(item);
                        }
                    }
                }
            }catch (Exception e) {
                System.out.println(e);
                e.printStackTrace();
            }finally {
                closeFTPConnect();
            }
        }else {
            fileNameDetails.put("code", 400);
            fileNameDetails.put("msg", "FTP服务器连接登录失败，请检查网络是否通畅。");
        }
        fileNameDetails.put("filelist", fileList);
        return fileNameDetails;
    }
}
